package com.song.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.song.context.BaseContext;
import com.song.dto.CategoryPageQueryDTO;
import com.song.entity.Category;
import com.song.exception.DeletionNotAllowedException;
import com.song.mapper.CategoryMapper;
import com.song.mapper.DishMapper;
import com.song.mapper.SetmealMapper;
import com.song.result.PageResult;
import com.song.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public Integer updateCategory(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(BaseContext.getCurrentId());
      return categoryMapper.updateCategory(category);
    }

    @Override
    public Integer deleteCategory(Long id) {
        //1.删除之前，判断该分类下是否有菜品,套餐中是否有该分类
        Integer dishCount = dishMapper.getDishCountByCategoryId(id);
        Integer setmealCount = setmealMapper.getMealCountByCategoryId(id);
        if(dishCount > 0 || setmealCount > 0){
            //有菜品或者套餐，不能删除
            throw new DeletionNotAllowedException("当前分类下有菜品或者套餐，不能删除");

        }
        return categoryMapper.deleteCategory(id);
    }
    //分类分页查询
    @Override
    public PageResult<Category> getCategoryPage(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        List<Category> categoryList = categoryMapper.getCategoryPage(categoryPageQueryDTO);
        Page<Category> page = (Page<Category>) categoryList;
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    @Override
    public Integer updateCategoryStatus(Integer status, Long id) {
        Category category = new Category();
        category.setId(id);
        category.setStatus(status);
        return categoryMapper.updateCategory(category);
    }

    @Override
    public Integer addCategory(Category category) {
      category.setStatus(1);
      return categoryMapper.addCategory(category);
    }

    //根据类型查询分类列表
    @Override
    public List<Category> getCategoryByType(Integer type) {
        return categoryMapper.getCategoryPage(CategoryPageQueryDTO.builder().type( type).build());
    }
}
